package com.geek.servlet;

import javax.annotation.Resource;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "jndiServlet", value = "/jndi-servlet")
public class JndiServlet extends HttpServlet {

  @Resource(lookup = "java:/comp/env", name = "jdbc/DemoDataSource")
  private DataSource mysqlDataSource;

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("连接信息: " + getConnection() );
//    queryUsers();
  }

  private Connection getConnection() {
    Connection connection = null;
    try {
      connection = mysqlDataSource.getConnection();
    } catch (SQLException throwable) {
      throwable.printStackTrace();
    }
    return connection;
  }

  private void queryUsers() {
    final String sql = "SELECT username FROM users WHERE ID = 1";
    Connection con = getConnection();
    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = con.prepareStatement(sql);
      rs = stmt.executeQuery(sql);
      // 循环输出查询结果
      while(rs.next()){
        System.out.print("查询结果: " + rs.getString("username"));
      }
    } catch (SQLException throwable) {
      throwable.printStackTrace();
    } finally {
      try {
        if(con != null){
          con.close();
        }
        if(stmt != null){
          stmt.close();
        }
        if(rs != null){
          rs.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}